package com.raychi.demo.servlet.buyer;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.raychi.demo.entity.Buyer;
import com.raychi.demo.util.BuyerUtil;
import com.raychi.demo.util.JdbcUtil;

public class BuyerUpdateServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int id = Integer.valueOf(req.getParameter("id"));
		Buyer buyer = getBuyerById(id);
		req.setAttribute("buyer", buyer);
		req.getRequestDispatcher("/product/updateBuyer.jsp").forward(req, resp);
	}
	private Buyer getBuyerById(int id) {
		Buyer buyer = null;
		Connection conn = null;
		try {
			conn = JdbcUtil.getConnection();
			Statement st = conn.createStatement();
			String sql = "select * from buyer where id=" + id;
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				buyer = BuyerUtil.createBuyer(rs);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		return buyer;
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			req.setCharacterEncoding("utf-8");
			String name = req.getParameter("name");
			int money = Integer.valueOf(req.getParameter("money"));
			int id = Integer.valueOf(req.getParameter("id"));
			updateBuyer(name, money, id);
			resp.sendRedirect(req.getContextPath() + "/buyer/");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	private void updateBuyer(String name, int money, int id)
			throws SQLException, ClassNotFoundException {
		Connection conn = JdbcUtil.getConnection();
		String sql = "update buyer set name = ?,money = ? where id =?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, name);
		ps.setInt(2, money);
		ps.setInt(3, id);
		ps.executeUpdate();
		conn.commit();
	}
	
}
